package com.gz.handler;

import com.gz.common.RedisConst;
import com.gz.entity.Book;
import com.gz.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class StorageRunner implements CommandLineRunner  {

    @Autowired
    private BookService bookService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    // 热销榜数据初始化
    @Override
    public void run(String... args) throws Exception {
        if (!redisTemplate.hasKey(RedisConst.BOOK_STORAGE)){
            List<Book> list = bookService.list();
            list.forEach(t->redisTemplate.opsForHash()
                    .put(RedisConst.BOOK_STORAGE,t.getId().toString(),t.getStoreCount()));
        }
        log.info("库存预热,初始化完成");
    }
}
